<?php
set_time_limit(0);
define('DOWNLOAD', 'images/brands/');
$url = 'http://list.hitao.taobao.com/allbrand.htm';
$conn = null;

$htm = file_get_contents($url);
$pat = "/(<dl[^>]*id=\"[\w]\">.*?<\/dl>)/is";

preg_match_all($pat,$htm,$data);

//var_dump($data[1][0]);
//$pat = "/<li>[^<]*?<a[^>]*href=[^>]*q=(.*+)?\"><img[^>]*?alt=\"([^\"]+)?\"[^>]*?src=\"([^\"]+)?\"><\/a><a[^>]*>[^<]*?<\/a>[^<]*?<\/li>/is";
//$pat = "/<li>(.*?)<\/li>/is";

$pat = "/<li> <a href=\"http:\/\/list\.hitao\.taobao\.com\/item_search\.htm\?q=(.+?)\"><img alt=\"(.+?)\" src=\"(.*?)\"><\/a><a[^>]+?>[^<]+?<\/a> <\/li>/is";

$categories = array(1=>'流行服饰','美肤美妆','时尚配饰','运动户外','3C数码','家居家电','母婴用品');

init_mysql();


for( $z = 0; $z < count($data[1]); $z++ )
{	
	preg_match_all($pat,$data[1][$z],$d);
	for($i = 0; $i < count($d[1]); $i++)
	{
		$brandcate = $z+1;
		$brandname = $d[2][$i];
		$imgpath = saveimage($d[3][$i]);
		$searchkey = $d[1][$i];
		$sql = "insert into enp_brands(`brandcate`,`brandname`,`imgpath`,`searchkey`) values ('$brandcate','$brandname','$imgpath','$searchkey')";
		mysql_query($sql);
		echo $sql.';'.'<br />';
	}
}

function init_mysql()
{
	global $conn;
	$conn = mysql_connect('localhost', 'root', 'zhuxueyi');
			mysql_select_db('taoke', $conn);
			mysql_query("set names utf8");
}

function saveimage( $url )
{
	$file = explode('/', $url);
	$filesave = DOWNLOAD . $file[count($file)-1];
	return download_file($url, $filesave);
}

function download_file( $file_uri, $file_save_name )
{
	//$data = file_get_contents( $file_uri );
	//write_file( $file_save_name, $data );
	return $file_save_name;
}

function write_file( $file_name, $data )
{
	$fp = fopen( $file_name, 'w' );
	if( $fp ) fwrite( $fp, $data );
	@fclose( $fp );
}
@mysql_close($conn);
?>